<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表 -->
      <el-table :data="roleList" border stripe style="margin-top: 15px; font-size:16px;">
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '']" type="flex" align="middle"
            v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row :class="i2 === 0 ? '' : 'bdtop'" type="flex" align="middle"
                v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="13">
                    <!-- 渲染三级权限 -->
                    <el-tag type="warning" v-for="item3 in item2.children" 
                    :key="item3.id" closable @close="tagClose(scope.row.id, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
                <!-- <el-tag>{{  }}</el-tag> -->
              </el-col>
            </el-row>
            <!-- <ul v-for="data in scope.row.children" :key="data.id">
              <li>{{ data.authName }}</li>
              <li>{{ data.path }}</li>
              <li>{{ data.children }}</li>
            </ul> -->
          </template>
        </el-table-column>
        <!-- 常规列表 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getRoleInfo(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRoleInfo(scope.row)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="giveRoleInfo(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!------------------------------------------------- 非文档流部分 ----------------------------------------------------->

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose"> 
      <!-- 主体部分 -->
      <el-form ref="addDialogFormRef" :rules="addDialogRules" :model="addDialogForm" label-width="80px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addDialogForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addDialogForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose"> 
      <!-- 主体部分 -->
      <el-form ref="editDialogFormRef" :rules="editDialogRules" :model="editDialogForm" label-width="80px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editDialogForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editDialogForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="giveDialogVisible" width="50%" @close="giveDialogClose"> 
      <!-- 主体部分 -->
      <el-tree
        :data="roleTreeData"
        :props="giveRoleProps"
        show-checkbox
        node-key="id"
        ref="tree"
        :default-expand-all = "true"
        :default-checked-keys="roleIdList"
        @check-change="handleCheckChange"
        @node-click="handleNodeClick">
      </el-tree>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="giveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="giveRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      // 当前角色所有已有三级权限的权限id
      roleIdList: [],
      roleTreeData: [],
      // 默认绑定的节点
      giveRoleProps: {
        label: 'authName',
        children: 'children'
      }, 
      addDialogVisible: false,
      editDialogVisible: false,
      giveDialogVisible: false,
      thisRoleId: '',
      addDialogForm: {
        roleName: '',
        roleDesc: ''
      },
      editDialogForm: {
        roleName: '',
        roleDesc: ''
      },
      addDialogRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 30, message: '角色名称长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 120, message: '角色描述长度在 1 到 120 个字符', trigger: 'blur' }
        ]
      },
      editDialogRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 30, message: '角色名称长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 120, message: '角色描述长度在 1 到 120 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 关闭第三级标签
    tagClose(roleId, rightId){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        // 根据角色id删除指定权限
        console.log(roleId, rightId)
        this.$http.delete(`roles/${roleId}/rights/${rightId}`).then(res => {
          if(res.data.meta.status !== 200){
            this.$message.error("取消权限失败: " + res.data.meta.msg)
          }else{
            this.$message.success("取消权限成功")
            this.getRolesList()
          }
        })
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },

    // 获取所有角色列表
    getRolesList() {
      this.$http.get('roles').then(res => {
        if(res.data.meta.status !== 200){
          this.$message.error("获取角色列表失败")
        }else{
          // console.log(res.data)
          this.roleList = res.data.data
        }
      })
    },
    addDialogClose() {
      // 关闭后清除校验结果
      this.$refs.addDialogFormRef.resetFields()
    },
    editDialogClose() {
      // 关闭后清除校验结果
      this.$refs.editDialogFormRef.resetFields()
    },

    // 请求添加角色
    addRoles() {
      // 预校验
      this.$refs.addDialogFormRef.validate(valid => {
        if(!valid){
          return
        }else{
          // 校验成功可以请求添加数据
          this.$http.post('roles', this.addDialogForm).then(res => {
            if(res.data.meta.status !== 201){
              this.$message.error("添加角色失败: " + res.data.meta.msg)
            }else {
              this.addDialogVisible = false
              this.$message.success("添加角色成功")
              this.getRolesList()
            }
          })
        }
      })
    },

    // 获取角色信息显示到修改对话框
    getRoleInfo(scopeRow) {
      this.editDialogVisible = true
      this.editDialogForm = {
        roleName: scopeRow.roleName,
        roleDesc: scopeRow.roleDesc
      }
      this.thisRoleId = scopeRow.id
    },

    // 发送修改角色请求
    editRoles() {
      this.$refs.editDialogFormRef.validate(valid => {
        if(!valid){
          return
        }else{
          // 校验成功可以请求修改数据
          this.$http.put(`roles/${this.thisRoleId}`, this.editDialogForm).then(res => {
            console.log(res.data)
            if(res.data.meta.status !== 200){
              this.$message.error("修改角色失败: " + res.data.meta.msg)
            }else {
              this.editDialogVisible = false
              this.$message.success("修改角色成功")
              this.getRolesList()
            }
          })
        }
      })
    },

    // 发送删除角色信息请求
    delRoleInfo(scopeRow) {
       this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          // 发送请求
          this.$http.delete(`roles/${scopeRow.id}`).then(res => {
            if(res.data.meta.status !== 200){
              this.$message.error("删除角色失败: " + res.data.meta.msg)
            }else{
              this.$message.success("删除角色成功")
              this.getRolesList()
            }
          })
        }).catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 关闭分配权限对话框
    giveDialogClose() {
      this.giveDialogVisible = false
      // 关闭对话框后重置树的状态
      this.roleIdList = []
    },

    // 分配权限对话框
    giveRoleInfo(scopeRow) {
      this.giveDialogVisible = true

      // 获取所有的权限 显示为树形图
      this.$http.get('rights/tree').then(res => {
        this.roleTreeData = res.data.data
        console.log(this.roleTreeData)
      })

      // 获取当前角色已有权限
      let allRoleInfo = scopeRow.children
      for (var i = 0; i < allRoleInfo.length; i++) {
        for (var j = 0; j < allRoleInfo[i].children.length; j++) {
          for (var k = 0; k < allRoleInfo[i].children[j].children.length; k++) {
            this.roleIdList.push(allRoleInfo[i].children[j].children[k].id)
            // console.log(this.roleIdList)
          }
        }
      }

      // 存储当前角色id
      this.thisRoleId = scopeRow.id
    },

    handleNodeClick(giveTreeData){
      console.log(giveTreeData);
    },
    
    handleCheckChange(data, checked, indeterminate) {
      // 
    },

    giveRoles() {
      // 获取半选中和选中状态的节点id
      // let allCheckArr = this.$refs.tree.getCheckedKeys()
      // let halfCheckArr = this.$refs.tree.getHalfCheckedKeys()
      // let checkList = allCheckArr.concat(halfCheckArr)
      
      const checkList = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ]
      
      // 根据api文档 需要将数组转换成以逗号拼接的字符串
      let checkStr = checkList.join(',')

      // 将得到的权限id请求给后端
      this.$http.post(`roles/${this.thisRoleId}/rights`, {
        rids: checkStr
      }).then(res => {
        if(res.data.meta.status !== 200) {
          this.$message.error(res.data.meta.msg)
        } else {
          this.$message.success(res.data.meta.msg)
          this.giveDialogVisible = false
          this.getRolesList()
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
  .el-tag {
    margin: 7px;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
</style>